//
//  UITextView+Category..swift
//  Super_WeiBo
//
//  Created by SuperMac on 16/6/8.
//  Copyright © 2016年 lc. All rights reserved.
//

import UIKit


extension UITextView
{
    /**
     传入模型设置textView的输入内容
     */
    func insertEmoticon(emoticon: Emoticon)
    {
        // 判断是否点击删除按钮
        if emoticon.isRemoveButton
        {
            deleteBackward()
        }
        
        // 判断是否是emoji表情
        if emoticon.emojiStr != nil
        {
            self.replaceRange(self.selectedTextRange!, withText: emoticon.emojiStr!)
        }
        // 判断当前点击是否为图片表情
        if emoticon.png != nil
        {
            // 创建表情字符串
//            let s = self.font!.lineHeight
            let imageText = EmoticonTextAttachment.imageText(emoticon, font: font!)
            
            // 拿到当前所有输入内容
            let strAll = NSMutableAttributedString(attributedString: self.attributedText)
            // 插入表情到当前光标所在位置
            let range = self.selectedRange
            strAll.replaceCharactersInRange(range, withAttributedString: imageText)
            // 给表情图片设置字体大小，避免后面添加emoji表情时出现大小Bug
            strAll.addAttribute(NSFontAttributeName, value: font!, range: NSRange(location: range.location, length: 1))
            // 将替换后的字符串赋值给UITextView
            self.attributedText = strAll
            // 恢复光标位置
            self.selectedRange = NSRange(location: range.location+1, length: 0)
            
            // 输入图片不会出发textViewDidChange代理方法，需要手动出发
            delegate?.textViewDidChange!(self)
        }
    }
    
    /**
     将textView中的AttributedText转换为string
     */
    func emoticonAttributedText() -> String
    {
        var strM = String()
        attributedText.enumerateAttributesInRange(NSRange(location: 0, length: attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (objc, range, _) in
            
            if objc["NSAttachment"] != nil
            {
                let attachment = objc["NSAttachment"] as! EmoticonTextAttachment
                // 图片
                strM += attachment.chs!
            }
            else
            {
                // 文字
                strM += (self.text as NSString).substringWithRange(range)
            }
        }
        return strM
    }
}